import { restArguments } from "../collections/invoke";
import delay from "./delay";

const debounce = function (func: Function, wait: number, immediate: any) {
  var timeout: number, result: any;
  var later = function (context: any, args: any) {
    timeout = null;
    if (args) result = func.apply(context, args);
  };


  function fn(...args: any[]) {
    if (timeout) clearTimeout(timeout);
    if (immediate) {
      var callNow = !timeout;
      timeout = setTimeout(later, wait);
      if (callNow) result = func.apply(this, args);
    } else {
      timeout = delay(later, wait, this, args);
    }

    return result;
  }


  fn.cancel = function () {
    clearTimeout(timeout);
    timeout = null;
  };

  return fn;
}